<?php
namespace Home\Controller;

use Think\Controller;

class TestController extends Controller
{
//    public function _initialize()
//    {
//        $table_name = "tsiteinfo_" . date("Ymd", time());
//        $this->table_name=$table_name;
//        $this->db = M($table_name);
//
//    }

    //写入数据库
    public function index()
    {
        header("Access-Control-Allow-Origin: *");
        if (I('url')) {
            //接收传过来的数据
            $data['url'] = $url = I('url');
            $data['title'] = $title = I('title');
            $data['description'] = $description = I('description');
            $data['keywords'] = $keywords = I('keywords');
            $data['refer'] = $refer = I('refer');
            $data['createtime'] = date("Ymd", time());
            $data['createtime'] = date("Ymd", time());
            /**方法一**/
            if (!empty($url)) {
                //传给夏雨，让他好判断
                header('Content-Type:application/json; charset=utf-8');
                $return_data['status'] = 1;
                echo json_encode($return_data);
                echo I('jsonp')."({'ret':'true'})";

                //url存在带问号的参数,则去掉url中？
                $pos = strpos($url, "?");
                if ($pos !== false) {
                    $pos2 = substr($url, $pos);
                    $url = str_replace($pos2, "", $url);
                }
                $data['url']=$url;

                /**************使用redis缓存url，作为判断当前url是否已经存在的方法********************/
                $redis = new \Redis;
                $redis->connect('127.0.0.1', 6379);

                //先检查昨天的key是否存在，存在的话，就删除
                $pre = date("Ymd", time() - 86400);
                $pre_set = $pre . "_url";//有序集合
                $pre_sorted_set = $pre . "_url_num";//无序集合

                $ex = $redis->exists($pre_set);//返回值：false/true
                $ex1 = $redis->exists($pre_sorted_set);
                if ($ex) $redis->delete($pre_set);
                if ($ex1) $redis->delete($pre_sorted_set);

                $cur = date("Ymd", time());
                $cur_set = $cur . "_url";
                $cur_sorted_set = $cur . "_url_num";

                if (!empty($title) || !empty($description) || !empty($keywords)) {
                    //redis无序集合的特性：集合元素唯一，如元素存在则无法写入并返回0，可以写入则写入并返回1
                    $res = $redis->sAdd($cur_set, $url);//返回值：1/0

                    if ($res) {
                        //表明该记录是第一次存入，则将该记录的url和默认分数1存入有序集合中，并将该记录写入数据库
                        //因是第一次存入，所以将分数设为1，
                        //返回：1/0 并且会将当前值更新分数（第二个参数）故需要用一个无序集合来判断是否是重复数据
                        $redis->zAdd($cur_sorted_set, 1, $url);

                        $rid = $this->db->data($data)->add();
                        if ($rid === false) {
                            $error = M($this->db)->getDbError();
                            $error = "【" . date("Y-m-d H:i:s", time()) . "】" . $error;
//                        file_put_contents('./error.log', $error . PHP_EOL, FILE_APPEND);
                        }
                    }else{
                        //表明该记录在无序集合中存在，则在有序集合中也一定存在，将有序集合中该记录的的分数加1
                        $redis->zIncrBy($cur_sorted_set,1,$url);//返回该数据新的分数值
                    }
                }
            }
        }
    }


    public function thjlst()
    {
        if (IS_GET) {
            $keyword = I('keyword', '', 'trim');
            $date = I('date');
            if (!empty($date)) {
                $table_name = "tsiteinfo_" . date("Ymd", strtotime($date));
                $this->db = M($table_name);
            }

            if (!empty($keyword)) {
                $keyword=trim($keyword,"|");
                $k_arr=explode("|",$keyword);

                $count=count($k_arr);
                foreach($k_arr as $k=>$v){
                    $alias="tb".$k;
                    $where=" where title like '%$v%' or description like '%$v%' or keywords like '%$v%'";
                    if($k===0){
                        if($count===1){ //当只提交了一个查询关键词时
                            $sql="select * from ".$this->table_name.$where;
                        }else{
                            $sql="(select * from ".$this->db.$where.") as $alias";
                        }
                    }elseif($k >0 && $k < $count-1){
                        $sql="(select * from ".$sql.$where.") as $alias";
                    }elseif($k+1===$count){ //键值+1=元素个数，表明已循环到最后一个元素
                        $sql="select * from ".$sql.$where;
                    }
                }

                //分页实现
//                $count = $this->db->where($where)->count();
//                $num = 100;//每页显示的条数
//
//                $page_c = new \Think\Page($count, $num);
//                $page = $page_c->show();
//                $lists = $this->db->where($where)->order("id desc")->limit($page_c->firstRow . ',' . $page_c->listRows)->select();
                $lists=$this->db->query($sql);
                $count=count($lists);

                //从redis中取出每条记录的num数
                $redis = new \Redis;
                $redis->connect('127.0.0.1', 6379);
                //$num_arr为保存num那一列的一维数组
                $num_arr=array();
                $key=date("Ymd", time())."_url_num";
                $num_arr=array();
                if($redis->exists($key)){
                    foreach($lists as $k=>$v){
                        $num_arr[$k]=$lists[$k]['num']=$redis->zscore($key,$v['url']);//命令返回有序集中，成员的分数值。
                    }
                    //对二维数组$lists按照字段num从大到小进行排序
                    array_multisort($num_arr,SORT_DESC,$lists);
                }

                $this->assign('keyword', $keyword);
                $this->assign('count',$count);
//                $this->assign('page', $page);
                $this->assign('lists', $lists);
            }
            $this->display();
        }

    }

    //服务器上有定时任务，每天复制一张以当天第二天日期
    public function copy_siteinfo()
    {
        $table_name = "siteinfo_" . date("Ymd", time() + 86400);
        $sql = "create table if not EXISTS $table_name like origin";
        $res = $this->db->execute($sql);
        if ($res === false) {
            $error = $this->db->getDbError();
            $error = "【" . date("Y-m-d H:i:s", time()) . "】" . $error;
            file_put_contents('./copy_error.log', $error . PHP_EOL, FILE_APPEND);
        }
    }

    public function murmurhash3_int($key, $seed = 0)
    {
        $key = array_values(unpack('C*', (string)$key));
        $klen = count($key);
        $h1 = (int)$seed;
        for ($i = 0, $bytes = $klen - ($remainder = $klen & 3); $i < $bytes;) {
            $k1 = $key[$i]
                | ($key[++$i] << 8)
                | ($key[++$i] << 16)
                | ($key[++$i] << 24);
            ++$i;
            $k1 = (((($k1 & 0xffff) * 0xcc9e2d51) + ((((($k1 >= 0 ? $k1 >> 16 : (($k1 & 0x7fffffff) >> 16) | 0x8000)) * 0xcc9e2d51) & 0xffff) << 16))) & 0xffffffff;
            $k1 = $k1 << 15 | ($k1 >= 0 ? $k1 >> 17 : (($k1 & 0x7fffffff) >> 17) | 0x4000);
            $k1 = (((($k1 & 0xffff) * 0x1b873593) + ((((($k1 >= 0 ? $k1 >> 16 : (($k1 & 0x7fffffff) >> 16) | 0x8000)) * 0x1b873593) & 0xffff) << 16))) & 0xffffffff;
            $h1 ^= $k1;
            $h1 = $h1 << 13 | ($h1 >= 0 ? $h1 >> 19 : (($h1 & 0x7fffffff) >> 19) | 0x1000);
            $h1b = (((($h1 & 0xffff) * 5) + ((((($h1 >= 0 ? $h1 >> 16 : (($h1 & 0x7fffffff) >> 16) | 0x8000)) * 5) & 0xffff) << 16))) & 0xffffffff;
            $h1 = ((($h1b & 0xffff) + 0x6b64) + ((((($h1b >= 0 ? $h1b >> 16 : (($h1b & 0x7fffffff) >> 16) | 0x8000)) + 0xe654) & 0xffff) << 16));
        }
        $k1 = 0;
        switch ($remainder) {
            case 3:
                $k1 ^= $key[$i + 2] << 16;
            case 2:
                $k1 ^= $key[$i + 1] << 8;
            case 1:
                $k1 ^= $key[$i];
                $k1 = ((($k1 & 0xffff) * 0xcc9e2d51) + ((((($k1 >= 0 ? $k1 >> 16 : (($k1 & 0x7fffffff) >> 16) | 0x8000)) * 0xcc9e2d51) & 0xffff) << 16)) & 0xffffffff;
                $k1 = $k1 << 15 | ($k1 >= 0 ? $k1 >> 17 : (($k1 & 0x7fffffff) >> 17) | 0x4000);
                $k1 = ((($k1 & 0xffff) * 0x1b873593) + ((((($k1 >= 0 ? $k1 >> 16 : (($k1 & 0x7fffffff) >> 16) | 0x8000)) * 0x1b873593) & 0xffff) << 16)) & 0xffffffff;
                $h1 ^= $k1;
        }
        $h1 ^= $klen;
        $h1 ^= ($h1 >= 0 ? $h1 >> 16 : (($h1 & 0x7fffffff) >> 16) | 0x8000);
        $h1 = ((($h1 & 0xffff) * 0x85ebca6b) + ((((($h1 >= 0 ? $h1 >> 16 : (($h1 & 0x7fffffff) >> 16) | 0x8000)) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff;
        $h1 ^= ($h1 >= 0 ? $h1 >> 13 : (($h1 & 0x7fffffff) >> 13) | 0x40000);
        $h1 = (((($h1 & 0xffff) * 0xc2b2ae35) + ((((($h1 >= 0 ? $h1 >> 16 : (($h1 & 0x7fffffff) >> 16) | 0x8000)) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff;
        $h1 ^= ($h1 >= 0 ? $h1 >> 16 : (($h1 & 0x7fffffff) >> 16) | 0x8000);
        return $h1;
    }

}